 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=144 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:39 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Send an email
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='JavaMail,email,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Send an email</div>

<div class='main-body'>
 
<br>The <a href="http://java.sun.com/products/javamail/">JavaMail</a> API
is not part of core Java SE, but an optional extension. In addition, it is required  
in Java Enterprise Edition. The JavaMail packages can be accessed in two ways :
<ul>
<li>
by placing <tt>j2ee.jar</tt> in the classpath</li>

<li>
or, by placing both <tt>mail.jar</tt> and <tt>activation.jar</tt> in the
classpath</li>
</ul>

The <tt>javax.mail</tt> API uses a properties file for reading server names and related configuration.
These settings will override any system defaults. Alternatively, the configuration
can be set directly in code, using the JavaMail API.

<p><b>Example</b>
<p>An email configuration file (to run the example, substitute valid values
for the uncommented items) :
<br>&nbsp;
<p><tt># Configuration file for javax.mail</tt>
<br><tt># If a value for an item is not provided, then</tt>
<br><tt># system defaults will be used. These items can</tt>
<br><tt># also be set in code.</tt>
<p><tt># Host whose mail services will be used</tt>
<br><tt># (Default value : localhost)</tt>
<br><tt>mail.host=mail.blah.com</tt>
<p><tt># Return address to appear on emails</tt>
<br><tt># (Default value : username@host)</tt>
<br><tt>mail.from=webmaster@blah.net</tt>
<p><tt># Other possible items include:</tt>
<br><tt># mail.user=</tt>
<br><tt># mail.store.protocol=</tt>
<br><tt># mail.transport.protocol=</tt>
<br><tt># mail.smtp.host=</tt>
<br><tt># mail.smtp.user=</tt>
<br><tt># mail.debug=</tt>
<p>A class which uses this file to send an email :
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> javax.mail.*;
<span class='keyword'>import</span> javax.mail.internet.*;

<span class='comment'>/**
* Simple demonstration of using the javax.mail API.
*
* Run from the command line. Please edit the implementation
* to use correct email addresses and host name.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Emailer {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main( String... aArguments ){
    Emailer emailer = <span class='keyword'>new</span> Emailer();
    <span class='comment'>//the domains of these email addresses should be valid,
</span>    <span class='comment'>//or the example will fail:
</span>    emailer.sendEmail(
      <span class='literal'>"fromblah@blah.com"</span>, <span class='literal'>"toblah@blah.com"</span>,
       <span class='literal'>"Testing 1-2-3"</span>, <span class='literal'>"blah blah blah"</span>
    );
   }

  <span class='comment'>/**
  * Send a single email.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> sendEmail(
    String aFromEmailAddr, String aToEmailAddr,
    String aSubject, String aBody
  ){
    <span class='comment'>//Here, no Authenticator argument is used (it is null).
</span>    <span class='comment'>//Authenticators are used to prompt the user for user
</span>    <span class='comment'>//name and password.
</span>    Session session = Session.getDefaultInstance( fMailServerConfig, <span class='keyword'>null</span> );
    MimeMessage message = <span class='keyword'>new</span> MimeMessage( session );
    <span class='keyword'>try</span> {
      <span class='comment'>//the "from" address may be set in code, or set in the
</span>      <span class='comment'>//config file under "mail.from" ; here, the latter style is used
</span>      <span class='comment'>//message.setFrom( new InternetAddress(aFromEmailAddr) );
</span>      message.addRecipient(
        Message.RecipientType.TO, <span class='keyword'>new</span> InternetAddress(aToEmailAddr)
      );
      message.setSubject( aSubject );
      message.setText( aBody );
      Transport.send( message );
    }
    <span class='keyword'>catch</span> (MessagingException ex){
      System.err.println(<span class='literal'>"Cannot send email. "</span> + ex);
    }
  }

  <span class='comment'>/**
  * Allows the config to be refreshed at runtime, instead of
  * requiring a restart.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> refreshConfig() {
    fMailServerConfig.clear();
    fetchConfig();
  }

  <span class='comment'>// PRIVATE //
</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> Properties fMailServerConfig = <span class='keyword'>new</span> Properties();

  <span class='keyword'>static</span> {
    fetchConfig();
  }

  <span class='comment'>/**
  * Open a specific text file containing mail server
  * parameters, and populate a corresponding Properties object.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> fetchConfig() {
    InputStream input = <span class='keyword'>null</span>;
    <span class='keyword'>try</span> {
      <span class='comment'>//If possible, one should try to avoid hard-coding a path in this
</span>      <span class='comment'>//manner; in a web application, one should place such a file in
</span>      <span class='comment'>//WEB-INF, and access it using ServletContext.getResourceAsStream.
</span>      <span class='comment'>//Another alternative is Class.getResourceAsStream.
</span>      <span class='comment'>//This file contains the javax.mail config properties mentioned above.
</span>      input = <span class='keyword'>new</span> FileInputStream( <span class='literal'>"C:&#092;&#092;Temp&#092;&#092;MyMailServer.txt"</span> );
      fMailServerConfig.load( input );
    }
    <span class='keyword'>catch</span> ( IOException ex ){
      System.err.println(<span class='literal'>"Cannot open and load mail server properties file."</span>);
    }
    <span class='keyword'>finally</span> {
      <span class='keyword'>try</span> {
        <span class='keyword'>if</span> ( input != <span class='keyword'>null</span> ) input.close();
      }
      <span class='keyword'>catch</span> ( IOException ex ){
        System.err.println( <span class='literal'>"Cannot close mail server properties file."</span> );
      }
    }
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction9163-2.html?Id=242'>Launch other applications</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='144'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=144 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:39 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
